//
//  FSMainViewController_Second.m
//  Trade
//
//  Created by 刘沿 on 16/4/6.
//  Copyright © 2016年 刘沿. All rights reserved.
//
#import "ideitworkViewController.h"
#import "workedViewController.h"
#import "comingthingViewController.h"
#import "FSMainViewController_Second.h"
#import "AuthHelper.h"

@interface FSHomeModel : FSBaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end

@implementation FSHomeModel

@end

@interface FSMainViewController_Second ()<UICollectionViewDelegateFlowLayout,SangforSDKDelegate>


@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

//模型属性
@property (nonatomic,strong) FSHomeModel *homeModel;

@property (nonatomic,strong) NSMutableArray *contentArray;

//存储plist数据
@property(nonatomic,strong)NSMutableArray * originalData;

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic, strong) AuthHelper *helper;


@end

@implementation FSMainViewController_Second

NSString *vpnIp1 =    @"122.224.123.170";  //vpn设备IP地址
NSString *userName1 = @"ccpitzjapp";             //用户名认证的用户名
NSString *password1 = @"ccpitzjappapp";                //用户名认证的密码

NSString *certName1 = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd1 =  @"";          //证书密码，如果服务端没有设置证书

static NSString * const reuseIdentifier = @"CellIdentifier";

-(NSMutableArray *)contentArray{
    if (_contentArray == nil) {
        
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;

}

-(void)request{
    
    
//    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]) {
//        
//        self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp1 port:443 delegate:self];
//        [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
//    }

        [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:@"exchmain" arrays:array method:KhomePqwoiunuMethod success:^(id JSON) {
        NSArray *tempArray  = JSON[@"data"];
                [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];

        NSDictionary * dict = [tempArray firstObject];
        self.homeModel = [[FSHomeModel alloc] initWitDictionary:dict];
   NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
//存储plist数据
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    
    [self.contentArray addObjectsFromArray:self.originalData];

        [self setupSubView];

    } failure:^(NSError *error) {
        
    }];
    
//    [self addtimer];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    
//    [self.timer invalidate];
//    
//    self.timer = nil;
    
}

- (void)viewDidLoad {
//        self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp1 port:443 delegate:self];
//        self.edgesForExtendedLayout = UIRectEdgeNone;

    [super viewDidLoad];
    [self request ];
//            self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp1 port:443 delegate:self];

    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 0, 5);
    self.flowLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 20 )/ 4 , ([UIScreen mainScreen].bounds.size.width - 20 )/ 4);
    self.flowLayout.minimumInteritemSpacing = 0;
   
//    [self addtimer];
    // 判断版本
[self upApp];
    [self setLeftItem];
    
            self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp1 port:443 delegate:self];

    //定时器
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(refreshBtnCount) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
          dispatch_sync(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
        });
    });
}
- (void)upApp{
 //获取app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];

        NSArray *array = @[@{@"veseion":appVersion},@{@"sName":userId}];

//    NSArray *array = @[@{@"veseion":appVersion}];

[HttpTools requestWithURL:KExchmain arrays:array method:@"updateDown" success:^(id JSON) {
         NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
            NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
    
    
    if ([index isEqualToString:@"1"]) {
            
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"程序已经更新，请卸载完以前的版本，再重新下载" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
                
                  [_helper logoutVpn];

   FSLoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
         [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];

    self.view.window.rootViewController = loginVC;
                
            }];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                if (url.length != 0) {
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
            
            
        }

    }failure:^(NSError *error) {
        
    }];

    

}


#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName1];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password1];
            //开始用户名密码认证
//            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
            //            证书认证
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName1];
                NSLog(@"PATH = %@",authPaths);
                //P12证书路径
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                //证书的密码
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd1];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
            /** 用户名密码认证 */
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName1];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password1];
            
            break;
            /** 无认证 */
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}


- (void)setLeftItem{
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] init];
    
    leftItem.title = @"返回";
    
    self.navigationItem.backBarButtonItem = leftItem;
}

- (void)addtimer{
    dispatch_async(dispatch_queue_create(0, 0), ^{
        
        //添加定时器
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(refreshBtnCount) userInfo:nil repeats:YES];
        
        self.timer = timer;
        
        [[NSRunLoop currentRunLoop] run];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            [self.collectionView reloadData];
        });
 
    });
    
    
}

- (void)refreshBtnCount{

    [self requset];

}

- (void)requset{
     NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
        NSArray *  array = @[@{@"userId":userId}];;
        [HttpTools requestWithURL:@"exchmain" arrays:array method:KhomePqwoiunuMethod success:^(id JSON) {
            NSArray *tempArray  = JSON[@"data"];
            NSDictionary * dict = [tempArray firstObject];
            self.homeModel = [[FSHomeModel alloc] initWitDictionary:dict];
            [self setupSubView];
        } failure:^(NSError *error) {
            
        }];
}

-(void)setupSubView{
    if ([self.homeModel.whetherExchange integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"待收文件"] || [dict[@"title"] isEqualToString:@"已收文件"] || [dict[@"title"] isEqualToString:@"已发文件"]) {
                [self.originalData removeObject:dict];
            }
            
        }
    }
    
    if([self.homeModel.whetherSms integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"短信平台"]) {
                [self.originalData removeObject:dict];
            }
        }
    }
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}

//退出按钮
- (IBAction)logout:(id)sender {
    

 UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:@"是否退出系统" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView show];

//    FSLoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
//    
//    self.view.window.rootViewController = loginVC;
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1){
 [_helper logoutVpn];
FSLoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
         [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];

    self.view.window.rootViewController = loginVC;
//     loginVC.type = @"1";



}
}

#pragma mark------数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    FSCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//plist 里的数据传过去
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;
    if ([dict[@"title"]isEqualToString:@"待收文件"]) {
        [cell.btnCount setTitle:self.homeModel.exchange forState:UIControlStateNormal];
        if ([self.homeModel.exchange integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    else if ([dict[@"title"] isEqualToString:@"待办文件"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    else if ([dict[@"title"] isEqualToString:@"待阅文件"]) {
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
     else if ([dict[@"title"] isEqualToString:@"待办事项"]) {
        [cell.btnCount setTitle:self.homeModel.ksmail forState:UIControlStateNormal];
        if ([self.homeModel.ksmail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    else if ([dict[@"title"] isEqualToString:@"邮件"]) {
        [cell.btnCount setTitle:self.homeModel.mail forState:UIControlStateNormal];
        if ([self.homeModel.mail integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }

    [cell layoutIfNeeded];
    
    return cell;
}

#pragma mark------代理方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    [self setupWithIndexPath:indexPath];

}

-(void)setupWithIndexPath:(NSIndexPath*)indexPath{
    NSDictionary * dict =  self.contentArray[indexPath.item];
    FSWaitReceiveController * dueInVC = (FSWaitReceiveController*)[self.storyboard instantiateViewControllerWithIdentifier:@"WaitReceive"];
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
     if ([dict[@"title"] isEqualToString:@"待办事项"]) {
   comingthingViewController *comthvc = (comingthingViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"comingthing"];
       [self.navigationController pushViewController:comthvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"已办事项"]) {
   ideitworkViewController *ideitvc = (ideitworkViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"ideit"];
    [self.navigationController pushViewController:ideitvc animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"办结事项"]) {
workedViewController *worked = (workedViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"worked"];
    [self.navigationController pushViewController:worked animated:YES];
    }
    if ([dict[@"title"] isEqualToString:@"待收文件"]) {
        dueInVC.vcType = WaitForSignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"已收文件"]){
        dueInVC.vcType = AlreadySignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已发文件"]){
        dueInVC.vcType = SenderSinType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"待办文件"]){
       
        FSupCommingWorkController *upComVC = [storyBoard instantiateViewControllerWithIdentifier:@"upVC"];
        
        [self.navigationController pushViewController:upComVC animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"已办文件"]){
        FSToDoingWorkController *todoVC = [storyBoard instantiateViewControllerWithIdentifier:@"toVC"];
        
        [self.navigationController pushViewController:todoVC animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"待阅文件"]){
        
        dueInVC.vcType = WaitForReadType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"电子公告"]){

        FSNoteViewController *noteVC = [storyBoard instantiateViewControllerWithIdentifier:@"noteVC"];
        
        [self.navigationController pushViewController:noteVC animated:YES];
 
        
    }else if ([dict[@"title"] isEqualToString:@"最新收文"]){

        FSNewReceiveController *ReceiveVC = [storyBoard instantiateViewControllerWithIdentifier:@"newReceVC"];
        
        [self.navigationController pushViewController:ReceiveVC animated:YES];

    }else if ([dict[@"title"] isEqualToString:@"最新发文"]){
        FSNewSendController *NewSendVC = [storyBoard instantiateViewControllerWithIdentifier:@"newSend"];
        
        [self.navigationController pushViewController:NewSendVC animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"短信平台"]){
        FSMessageController * smsVC = (FSMessageController*)[self.storyboard instantiateViewControllerWithIdentifier:@"MessageVC"];
        smsVC.vcType = SMSViewControllerType;
        [self.navigationController pushViewController:smsVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"通讯录"]){
    
     UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"MaoCuHui" bundle:nil];
    FSDepAdressViewController * depVC = (FSDepAdressViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"DepAddressID" ];
//    NSDictionary * dict = self.contents[indexPath.row];
    depVC.path = @"ccpithzs";
    //ccpithzs
    [self.navigationController pushViewController:depVC animated:YES];
//        FSAddressViewController * addressVC = (FSAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
//        [self.navigationController pushViewController:addressVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"邮件"]){
        FSHomeEmailViewController * homeEmailVC = (FSHomeEmailViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HomeEmailID"];
        [self.navigationController pushViewController:homeEmailVC animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"外网网站"]){
        
        FSWaiWangViewController *waiwang = [self.storyboard instantiateViewControllerWithIdentifier:@"WaiWangID"];
        
        [self.navigationController pushViewController:waiwang animated:YES];
        
    }else if ([dict[@"title"] isEqualToString:@"专项网站"]){

        FSNeiWangViewController *waiwang = [self.storyboard instantiateViewControllerWithIdentifier:@"NeiWangID"];
        
        [self.navigationController pushViewController:waiwang animated:YES];
  
    }


}



@end














